package com.game.ws;

import com.game.protobuf.PFMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import java.util.List;

public class WebSocketMessageEncoder extends MessageToMessageEncoder<PFMessage> {
    protected void encode(ChannelHandlerContext ctx, PFMessage msg, List<Object> out) throws Exception {
        int len = 0;
        if (msg.data != null)
            len = msg.data.length;
        ByteBuf byteBuf = Unpooled.buffer(len + 4);
        byteBuf.writeShort(msg.messageType);
        byteBuf.writeShort(msg.cmd);
        byteBuf.writeBytes(msg.data);
        out.add(new BinaryWebSocketFrame(byteBuf));
    }
}
